define([
    'require',
    'jquery',
    'header',
    'nav',
    'message',
    'pagination',
    'usergroup_manage',
    'imgUploader',
    'blocksit',
    'picture_browser',
    'constants',
    'bigwe_component',
    'tooltip',
    'plat_public',
    'unauthor',
    'api',
], function(require, $) {
    var groupManage = require('usergroup_manage'),
        imgUploader = require('imgUploader'),
        message = require('message'),
        pb = require('picture_browser'),
        route = require('constants'),
        deleteConfirmShowBottom = require('bigwe_component').deleteConfirmShowBottom,
        InterFace = require('api'),
        data_img_id;
    /*
     * 分组
     */
    var groupManageConfig = {
        requestType: 'post',
        groupType: 'image',
        addNewUrl: InterFace.MY_PICTURE.ADD_IMG_GROUP, // 添加分组数据接口
        addParamName: 'cgn', // 添加分组的参数名
        deleteUrl: InterFace.MY_PICTURE.DEL_IMG_GROUP, // 删除分组数据接口
        deleteParamName: 'cgid', // 删除分组的参数名
        modifyUrl: InterFace.MY_PICTURE.ADD_IMG_GROUP,
        dataUnit: '张',
        modifyParam: { // 修改分组的参数名
            groupId: 'cgid',
            groupName: 'cgn'
        },
        userGroupData: null, // 未加载请定义成null 加载完成如果没有数据赋值成空数组
        // 列表展示数据赋值
        deleteCallback: function(data, deleteID) {
            if (deleteID && ($(".tool_s").find('span[data-cgid="' + deleteID + '"]').hasClass('green') || $('select.group_more').val() == deleteID)) {
                $('.group_list > span').eq(0).trigger('click')
            }else {
                img_group_id = $('.group_list').find('span.green').data('cgid') || $('select.group_more').val();
            }
            tag_list(this.userGroupData);
        },
        addCallback: function(data) {
            img_group_id = $('.group_list').find('span.green').data('cgid') || $('select.group_more').val();
            tag_list(this.userGroupData);
            if (data_img_id) {
                cg(data_img_id, data.id);
            }
        },
        modifyCallback: function() {
            img_group_id = $('.group_list').find('span.green').data('cgid') || $('select.group_more').val();
            tag_list(this.userGroupData);
        }
    }
    groupManage.init(groupManageConfig);
    var img_group_id;

    $.ajax({
        type: 'post',
        dataType: 'json',
        url: InterFace.MY_PICTURE.GET_GROUP,
        success: function(data) {
            if (data.ret == 0) {
                var group = data.data;
                groupManageConfig.userGroupData = group;
                tag_list(group);
            }
        }
    });

    function tag_list(grouping) {
        $(".article_grouping > div.group_list > span").not(':first').remove();
        $(".group_more > option").not(':first').remove();
        $("select.group_more").addClass('hide');
        var group_html = '',
            more_html = '';
        if (grouping.length > 0) {
            for (var i in grouping) {
                if (i < 4) {
                    group_html += '<span data-cgid="' + grouping[i].id + '"'+((img_group_id == grouping[i].id) ? ' class="green"' : '') +'>' + grouping[i].group_name + '</span>';
                } else {
                    more_html += '<option value="' + grouping[i].id + '"'+((img_group_id == grouping[i].id) ? ' selected = "selected"' : '') +'>' + grouping[i].group_name + '</option>';
                }
            }
        }

        if (grouping.length > 4) {
            $(".group_more").removeClass('hide');
        }

        $(".article_grouping > div.group_list").append(group_html);
        $("select.group_more").append(more_html);
        $('select.group_more').selectpicker('refresh');
    }

    var params = {
            p: 1,
            l: 20,
        },
        paging_sign = true,
        image_data = [],
        group_num;

    var content = $('.main_left');

    picture_list(params);

    function picture_list(json) {
        message.show('正在加载...');
        $.ajax({
            type: 'post',
            url: InterFace.MY_PICTURE.MY_IMG,
            data: json,
            success: function(data) {
                var json = (typeof data === 'string' ? $.parseJSON(data) : data).data;
                var arts = json.images;
                $('.altogether .total_number').text(json.total);
                var list_html = '';
                var _manager = content.find('.batch_manager').data('manager');
                if (arts.length > 0) {
                    image_data = arts;
                    for (var i in arts) {
                        list_html += '<div class="picture_item' + (_manager ? '' : ' active') + '">' +
                            '<img src="' + arts[i].image + '?imageView2/2/w/225" onerror="this.src=\'/Public/dev/images/wuyulantu.png\';"/>' +
                            '<div class="shade"> <p>' + (arts[i].title || '暂无标题') + '</p>' +
                            '<div class="icon_btn clearfix">' +
                            '<span class="publish_status pull-left">' + ((arts[i].is_show == 1) ? '已发布' : '未发布') + '</span>';
                        if (arts[i].is_show == 0) {
                            list_html += '<span class="iconfont icon-chuangzuo pull-right edit_pic" data-toggle="tooltip" title="编辑"></span>';
                        }
                        list_html += '<a class="iconfont icon-fasong pull-right" data-toggle="tooltip" title="发送" href="/sending?pid=' + arts[i].image_id + '" target="_blank"></a>' +
                            '<span class="iconfont icon-fenxiang pull-right">' +
                            '<div class="share"><a title="分享到QQ空间" class="qzone" href="javascript:void(0);"></a><a title="分享到新浪微博" class="sina" href="javascript:void(0);"></a>' +
                            '</div></span></div></div>' +
                            '<div class="print_masking' + (_manager ? ' fade' : '') + '"><div class="backdrop"></div><span class="iconfont icon-zhengque"></span></div>';
                        if (arts[i].is_show == 1) {
                            list_html += '<div class="picture_manager fade">已发布</div>';
                        }
                        list_html += '</div>';
                    }
                } else {
                    list_html = '<p><span class="glyphicon glyphicon-flash"></span>暂无图片</p>';
                }

                $('.picture_list').empty().append(list_html).BlocksIt({
                    numOfCol: 4,
                    offsetX: 5,
                    offsetY: 5
                });
                content.find('.choice_num').html('点击选择要批量操作的图片');
                if (paging_sign) {
                    paging(json.total);
                }
            },
            complete: function(data) {
                var json = typeof data.responseText === 'string' ? $.parseJSON(data.responseText) : data.responseText;
                // 判断图片加载状况，加载完成后回调
                isImgLoad(function() {
                    message.hide();
                    (json.data.total > 20) ? ($('.paging').show()) : ($('.paging').hide());
                    $('.picture_list').BlocksIt('reload').children().css({ opacity: '1' })
                });
                // $("[data-toggle='tooltip']").tooltip();
            }
        })
    }

    function paging(total) {
        if (paging_sign && params.p != 1) {
            var current_page = params.p - 1;
        }
        $(".paging").pagination(total, {
            num_edge_entries: 2,
            items_per_page: 20,
            current_page: current_page,
            prev_text: '上一页',
            next_text: '下一页',
            callback: function(_index, jq) {
                if (paging_sign) {
                    return;
                } else {
                    params.p = _index + 1;
                    picture_list(params);
                }
            }
        });
        paging_sign = false;
    }

    var t_img; // 定时器
    var isLoad = true; // 控制变量

    // 判断图片加载的函数
    function isImgLoad(callback) {
        // 查找所有封面图，迭代处理
        $('.picture_list img').each(function() {
            // 找到为0就将isLoad设为false，并退出each
            if (this.height === 0) {
                isLoad = false;
                return false;
            }
        });
        // 为true，没有发现为0的。加载完毕
        if (isLoad) {
            clearTimeout(t_img); // 清除定时器
            // 回调函数
            callback();
            // 为false，因为找到了没有加载完成的图，将调用定时器递归
        } else {
            isLoad = true;
            t_img = setTimeout(function() {
                isImgLoad(callback); // 递归扫描
            }, 500); // 我这里设置的是500毫秒就扫描一次，可以自己调整
        }
    }

    $('.selectpicker').selectpicker({ size: 4 });

    /*搜索*/
    content.find('.search_btn').click(function() {
        params.p = 1;
        params.key = content.find('#search_text').val();

        paging_sign = true;
        picture_list(params);
    });

    /*上传图片按钮*/
    imgUploader.init('upload_pictures', function(data) {
        picture_list(params);
    });

    /*编辑图片保存*/
    imgUploader.doSave = function(data) {
        picture_list(params);
    };

    /*批量管理*/
    content.find('.batch_manager').click(function() {
        if ($(this).data('manager')) {
            $(this).data('manager', false);
            $(this).text('批量管理');
            $('.action_btn,.choice_num').addClass('hide');
            $('.article_grouping,.search,#upload_pictures,.altogether').removeClass('hide');
            content.find('.picture_item').addClass('active');
            content.find('.print_masking').removeClass('fade in');
            content.find('.choice_num').html('点击选择要批量操作的图片');
            content.find('.action_btn > button').attr('disabled', true);
            content.find('.picture_manager').removeClass('in');
        } else {
            $(this).data('manager', true);
            $(this).text('取消管理');
            $('.action_btn,.choice_num').removeClass('hide');
            $('.article_grouping,.search,#upload_pictures,.altogether').addClass('hide');
            content.find('.picture_item').removeClass('active');
            content.find('.print_masking').addClass('fade');
            content.find('.picture_manager').addClass('in');
        }
    })

    /*选中图片*/
    content.on('click', '.print_masking', function() {
        if ($(this).hasClass('in')) {
            $(this).removeClass('in');
        } else if (content.find('.print_masking.fade.in').length == 10) {
            message.showWarning('最多只能选择10张图片批量管理哦！', message.showTime);
            return;
        } else {
            $(this).addClass('in');
        }
        if (content.find('.print_masking.fade.in').length > 0) {
            content.find('.action_btn > button').removeAttr('disabled');
            content.find('.choice_num').html('已选<span class="green total_number">' + content.find('.print_masking.fade.in').length + '</span>张');
        } else {
            content.find('.action_btn > button').attr('disabled', true);
            content.find('.choice_num').html('点击选择要批量操作的图片');
        }
    })

    /*分组切换*/
    content.on('change', 'select.group_more', function() {
        if ($(this).val() != '') {
            $('.group_list').children().removeClass('green');
            $('.group_more').addClass('green');
            paging_sign = true;
            params.p = 1;
            params.cgid = $(this).val();
            picture_list(params);
        }
    });
    content.on('click', '.group_list > span', function() {
        if ($(this).hasClass('green')) {
            return false;
        }
        if ($('select.group_more').val() != '') {
            $('.group_more').removeClass('green');
            $('select.group_more').val('');
            $('select.group_more').selectpicker('refresh');
        }
        $(this).addClass('green').siblings().removeClass('green');
        paging_sign = true;
        params.p = 1;
        params.cgid = $(this).data('cgid');
        picture_list(params);
    });

    /*发布状态切换*/

    content.on('change', 'select.release_select', function() {
        paging_sign = true;
        params.p = 1;
        params.is_show = $(this).val();
        picture_list(params);
    });

    /*点击图片预览*/
    $('.picture_list').on('click', 'img', function() {
        pb.doPreviewPicture(image_data, undefined, $(this).parent().index());
    });

    /*分享*/
    var a, b, s, t = 0;
    s = {
        title: '',
    }, t = {
        jiathis: function(a, b) {
            window.open("http://www.jiathis.com/send/?webid=" + a + "&url=" + encodeURIComponent(b.url) + "&summary=" + encodeURIComponent(b.summary) + "&uid=2118247&pic=" + encodeURIComponent(b.img) + "&appkey=" + b.appkey);
        }
    }, $(".picture_list").on('click', '.share a', function(a) {
        var user_login = $('#user_login').val();
        var i = $(this).parents('.picture_item').index();

        if (user_login == '') {
            a.preventDefault();
            a.stopImmediatePropagation();
            $('#login-modal').modal('show');
            login.loginSuccessAndContinue = $.proxy(function() {
                $(this).trigger('click');
            }, this);

        } else {
            var _url = 'http://' + window.location.host + '/search/img_detail/my?pid=' + image_data[i].image_id + '&user=' + $('#user_login').val();
            a.stopPropagation();
            s.img = image_data[i].img_url;
            s.url = _url;
            s.summary = image_data[i].title == '' ? '分享图片' : image_data[i].title;
            share(a.target.className);
            a.preventDefault();
        }
    });

    function share(c) {
        switch (c) {
            case "qzone":
                s.appkey = 101286682;
                t.jiathis("qzone", s);
                break;
            case "sina":
                s.appkey = 2121870539;
                t.jiathis("tsina", s);
                break;
        }
    }

    /*编辑*/
    $('.picture_list').on('click', '.edit_pic', function() {
        empty_val();
        var i = $(this).parents('.picture_item').index();

        var title = image_data[i].title,
            image_id = image_data[i].image_id,
            label = image_data[i].tags,
            img_src = image_data[i].img_url,
            classify = image_data[i].category_code;

        $('.img_name').val(title);
        $('#imageId').val(image_id);
        if (label.length > 0) {
            for (var k in label) {
                $('.custom-tag').append('<button type="button" title="' + label[k] + '">' + label[k] + '</button>');
            }
        }
        if (classify) {
            $('.video_classify').val(classify);
        }
        $('.selectpicker').selectpicker('refresh');
        $('.image_preview').append('<div id="example_image_qiniu" style="background-image:url(' + img_src + ')"></div>')
        $('#img-upload-modal').modal('show');
        $('.img_name').trigger('propertychange');
    });

    function empty_val() {
        $('#img-upload-modal input').val('');
        $('.custom-tag').html('');
        $('.video_classify').val('未分类');
        $('.select-tag').val('请选择');
        $('.selectpicker').selectpicker('refresh');
        $('.system-tag').children().remove();
        $('.image_preview').children().remove();
    }

    /*移动分组*/
    content.find(".action_group").click(function groupmove(e) {
        e = e || event;
        e.stopPropagation();
        var groupData = groupManageConfig.userGroupData;
        var groupsHtml = '';

        var img_id = "";
        $(".picture_list > div .print_masking").each(function() {
            if ($(this).hasClass('fade in')) {
                var i = $(this).parents('.picture_item').index();
                if (img_id.length > 1) {
                    img_id += ",";
                }
                img_id += image_data[i].image_id;
            }
        });

        if (groupData.length < 1) {
            addGrouping(this, img_id);
            return;
        }
        groupsHtml += '<div image_id="' + img_id + '" class="category-tab" style="display: block;">';
        var cacl = 0;
        for (i in groupData) {
            if (cacl == 0) {
                groupsHtml += '<div class="category" target_group="' + groupData[i].id + '"><div class="arrow"></div>' + groupData[i].group_name + '</div>';
                cacl++;
            } else {
                groupsHtml += '<div class="category" target_group="' + groupData[i].id + '">' + groupData[i].group_name + '</div>';
                cacl++;
            }
        }
        groupsHtml += '</div>';

        var left = 0,
            top = 0;

        var thisHeight = $(this).outerHeight(),
            thisWidth = $(this).outerWidth(),
            thisTop = $(this).offset().top,
            thisLeft = $(this).offset().left;
        left = thisLeft + thisWidth - thisWidth / 2 + 58;
        top = thisTop + thisHeight - thisHeight / 2 - 20;

        $('.category-tab').remove();
        $('body').append($(groupsHtml).css({
            left: left,
            top: top
        }));

        $(document).bind('click.category', function() {
            $('.category-tab').remove();
            $(document).unbind('click.category');
        });
    });

    function addGrouping(obj, img_id) {
        var _this = $(obj);
        var type = event.srcElement.type;

        $("body").append('<div class="add_grouping">' +
            '<img src="' + route.resPath + '/images/Triangle-up.png">' +
            '<p>您还没有分组，请添加分组</p>' +
            '<input type="text" value="" maxlength="30" class="sure_val"><br/>' +
            '<button type="button" class="btn-success sure">确定</button>' +
            '<button type="button" class="btn-default btn_cancel" onclick="$(this).parent().remove()">取消</button>' +
            '</p>' +
            '</div>');
        $('.add_grouping').css({
            left: _this.offset().left - $('.add_grouping').width() / 2,
            top: _this.offset().top + $('.add_grouping').height() / 3,
        });

        $('.sure_val').focus();
        $('.sure_val').on('keyup', function(e) {
            e = e || event;
            if (e.keyCode == 13) {
                //判断是否按下的enter按键(回车键)
                $('.add_grouping > .sure').trigger('click');
            }
        });

        $('.add_grouping > .sure').click(function() {
            var _group = $('.sure_val').val();
            if (_group) {
                data_img_id = img_id;
                $(this).parent().remove();
                groupManage.commonAddGroup(_group);
            } else {
                message.show('请输入分组名', 1500);
                $('.sure_val').focus();
            }
        });
        /**
         * 点击其他地方隐藏
         */
        $(document).bind('click.add_grouping', function(e) {
            var e = e || window.event; //浏览器兼容性 
            var elem = e.target || e.srcElement;
            while (elem) { //循环判断至跟节点，防止点击的是div子元素 
                if (elem.className && elem.className == 'add_grouping') {
                    return;
                }
                elem = elem.parentNode;
            }

            $(".add_grouping").remove(); //点击的不是div或其子元素 
            $(document).unbind("click.add_grouping");
        });
    }

    $(document).on('click', '.category-tab .category', cg);


    function cg(s, d) {
        if (d) {
            var cd = s,
                cgid = d;
        } else {
            var cd = $(this).parent().attr('image_id'),
                cgid = $(this).attr('target_group');
        }

        $.ajax({
            type: 'post',
            url: InterFace.MY_PICTURE.CHANGE_GROUP,
            data: {
                cgid: cgid,
                cd: cd,
            },
            success: function(data) {
                var data = typeof data === 'string' ? $.parseJSON(data) : data;
                if (data.ret == 0) {
                    message.show('操作成功！', message.showTime);
                    group_id();
                    if ($(".group_list > span.green").text() != '全部') {
                        paging_sign = true;
                        picture_list(params);
                    }
                } else {
                    message.showWarning('您还没有分组或者该图文已存在您唯一分组中', message.showTime);
                }
            }
        })
    };
    /*分组文章数同步*/
    function group_id() {
        $.ajax({
            type: 'post',
            dataType: 'json',
            url: InterFace.MY_PICTURE.GET_GROUP,
            data: {
                rt: 'article'
            },
            success: function(data) {
                var arts = data.data;
                for (var i in arts) {
                    $('[groupid=\"' + arts[i].id + '\"]').find('.battery-number').text(arts[i].group_num);
                }
            }
        });
    }

    /*删除*/
    content.find(".action_delete").click(function() {
        var img_id = "";
        $(".picture_list > div .print_masking").each(function() {
            if ($(this).hasClass('fade in')) {
                var i = $(this).parents('.picture_item').index();
                if (img_id.length > 1) {
                    img_id += ",";
                }
                img_id += image_data[i].image_id;
            }
        });
        deleteConfirmShowBottom({
            obj: $(this),
            url: InterFace.MY_PICTURE.DELETE_IMG,
            param: {
                cd: img_id
            },
            fun: function(data) {
                var data = typeof data === 'string' ? $.parseJSON(data) : data;
                if (data.ret == 0) {

                    if (img_id.split(',').length == $('.picture_list > div').length && params.p != 1) {
                        paging_sign = true;
                        if (params.p == $('.paging .next').prev().text()) {
                            params.p = $('.paging .next').prev().text() - 1;
                        }
                    }
                    content.find('.action_btn > button').attr('disabled', true);
                    picture_list(params);
                    group_id();
                }
            }
        })
    });

    /*发布*/
    content.on('click', '.action_publish', function() {
        var img_id = "";
        $(".picture_list > div .print_masking").each(function() {
            if ($(this).hasClass('fade in')) {
                var i = $(this).parents('.picture_item').index();
                if (img_id.length > 1) {
                    img_id += ",";
                }
                img_id += image_data[i].image_id;
            }
        });
        deleteConfirmShowBottom({
            obj: $(this),
            text: '已发布图片将不会再次发布。',
            url: InterFace.MY_PICTURE.DO_PUBLISH_IMG,
            type: 'post',
            param: {
                pids: img_id
            },
            fun: function(data) {
                message.show('发布中...');
                var data = typeof data === 'string' ? $.parseJSON(data) : data;
                if (data.ret == 99999) {
                    if (img_id.split(',').length == $('.picture_list > div').length && params.p != 1) {
                        paging_sign = true;
                        if (params.p == $('.paging .next').prev().text()) {
                            params.p = $('.paging .next').prev().text() - 1;
                        }
                    }
                    picture_list(params);
                    message.show('发布成功！',message.showTime);
                }else {
                    message.showWarning(data.msg,message.showTime);
                }
            }
        })
    });

    /*同步到微信*/
    var defined = require('plat_public');
    var bwAuthor = require('unauthor');
    var synchro_gzh={};
	var _ids;

    content.on('click','.action_sync', function() {
        _ids = '';
        $(".picture_list > div .print_masking").each(function() {
            if ($(this).hasClass('fade in')) {
                var i = $(this).parents('.picture_item').index();
                if (_ids.length > 1) {
                    _ids += ",";
                }
                _ids += image_data[i].image_id;
            }
        });
        $('#public_list').modal('show');
    });

    defined.sure = function(data) {
    	synchro_gzh = data;
        if (data.verify_type_info == -1) {
            gzh_login(not_certified);
        } else {
            certified(synchro_gzh);
        }
    }

    function certified(data) {
        message.show('同步中...', message.showTime);
        $.ajax({
            type: 'post',
            url: InterFace.COMMON.IMAGES_ASYNSEND,
            data: {
            	image_ids: _ids,
            	app_id: synchro_gzh.app_id
            },
            success: function(data) {
                var data = (data === '' ? data : $.parseJSON(data));
                if (data.ret != 99999) {
                    message.showWarning(data.msg, message.showTime);
                } else {
                    message.show('同步完成，请您留意系统通知状态！',message.showTime);
                }
            }
        })
    }

    function gzh_login(fn) {
        var authordata = {
            login_account: synchro_gzh.login_account,
            appid: synchro_gzh.app_id
        }
        if (!synchro_gzh.login_account) {
            authordata.isNewAuthor = !0
        } else {
            authordata.isNewAuthor = 0;
        }
        bwAuthor.doAuthorOperate(authordata, function(data) {
            synchro_gzh.login_account = data.login_account;
            fn();
        });
    }

    function not_certified(data) {
        message.show('同步中...', message.showTime);
        $.ajax({
            type: 'post',
            url: InterFace.COMMON.IMAGES_ASYNSIMSEND,
            data: {
            	image_ids: _ids,
            	login_account: synchro_gzh.login_account,
            },
            success: function(data) {
                var data = (data === '' ? data : $.parseJSON(data));
                if (data.ret != 99999) {
                    message.showWarning(data.msg, message.showTime);
                } else {
                    message.show('同步完成，请您留意系统通知状态！',message.showTime);
                }
            }
        })
    }
})